package org.hy.pay.common.core.dao.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.hy.pay.common.core.BaseEntity;
import org.hy.pay.common.core.dao.BaseDao;
import org.hy.pay.common.core.page.PageBean;
import org.hy.pay.common.core.page.PageParam;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.hy.pay.common.core.exception.BizException;

public  abstract class BaseDaoImpl<T extends BaseEntity>  extends SqlSessionDaoSupport implements BaseDao<T>{
    private static final Log LOG = LogFactory.getLog(BaseDaoImpl.class);
    
    public static final String SQL_INSERT = "insert";
    public static final String SQL_BATCH_INSERT = "batchInsert";
    public static final String SQL_UPDATE_BY_ID = "updateByPrimaryKey";
    public static final String SQL_BATCH_UPDATE_BY_IDS = "batchUpdateByIds";
    public static final String SQL_BATCH_UPDATE_BY_COLUMN = "batchUpdateByColumn";
	public static final String SQL_SELECT_BY_ID ="selectByPrimaryKey" ;
	public static final String SQL_LIST_BY_COLUMN = "listByColumn";
	public static final String SQL_LIST_BY ="listBy";
	public static final String SQL_LIST_PAGE_COUNT = "listPageCount";
	public static final String SQL_DELETE_BY_ID = "deleteByPrimaryKey";
	public static final String SQL_DELETE_BY_IDS = "batchDeleteByIds";
	public static final String SQL_BATCH_DELETE_BY_COLUMN = "batchDeleteByColumn";
	public static final String SQL_LIST_PAGE = "listPage";
	public static final String SQL_COUNT_BY_PAGE_PARAM ="countByPageParam";
  
	
	/**
     * 注入SqlSessionTemplate实例(要求Spring中进行SqlSessionTemplate的配置).
     * 可以调用sessionTemplate完成数据库操作.
     */




    public SqlSession getSqlSession() {
        return super.getSqlSession();
    }
	
	
	 @Autowired
	 public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate)
	    {
	     super.setSqlSessionTemplate(sqlSessionTemplate);
	    }
	


    /**
     * 插入单条数据
     */
	public int insert(T entity) {
		int result = getSqlSession().insert(getStatement(SQL_INSERT), entity);
		if(result <= 0){
			throw BizException.DB_INSERT_RESULT_0.newInstance("数据库操作,insert返回0.{%s}", getStatement(SQL_INSERT));
		}
		return result;
	}
	/**
	 * 批量插入
	 */
	public int insert(List<T> list) {
		if(list.isEmpty() || list.size() == 0){
			return 0;
		}
		int result =this.getSqlSession().insert(getStatement(SQL_BATCH_INSERT), list);
		if(result <= 0){
			throw BizException.DB_INSERT_RESULT_0.newInstance("数据库操作,batinsert返回0.{%s}", getStatement(SQL_BATCH_INSERT));
		}
		return result;
	}

	public int update(T entity) {
		entity.setEditTime(new Date());
		int result =this.getSqlSession().update(getStatement(SQL_UPDATE_BY_ID),entity);
		if(result <= 0){
			throw BizException.DB_UPDATE_RESULT_0.newInstance("数据库操作,updatePrimaryKey返回0.{%s}", getStatement(SQL_UPDATE_BY_ID));
		}
		return result;
	}

	public int update(List<T> list) {
		if(list.isEmpty() || list.size() == 0){
			return 0;
		}
		int result =this.getSqlSession().update(getStatement(SQL_BATCH_UPDATE_BY_IDS), list);
		if(result <= 0){
			throw BizException.DB_UPDATE_RESULT_0.newInstance("数据库操作,BatchUpdateByIds返回0.{%s}", getStatement(SQL_BATCH_UPDATE_BY_IDS));
		}
		return result;
	}

	public int update(Map<String, Object> paramMap) {
		if(paramMap == null){
			return 0;
		}
		int result =this.getSqlSession().update(getStatement(SQL_BATCH_UPDATE_BY_COLUMN), paramMap);
		if(result <= 0){
			throw BizException.DB_UPDATE_RESULT_0.newInstance("数据库操作,BatchUpdateByColumn返回0.{%s}", getStatement(SQL_BATCH_UPDATE_BY_COLUMN));
		}
		return result;
	}
	/**
	 * 根据ID 查询
	 */
	public T getById(String id) {
		return this.getSqlSession().selectOne(getStatement(SQL_SELECT_BY_ID),id);
	}

	public T getByColumn(Map<String, Object> paramMap) {
		if(paramMap == null){
			return null;
		}
		return this.getSqlSession().selectOne(getStatement(SQL_LIST_BY_COLUMN),paramMap);
	}
    /**
     * 根据条件查询
     */
	public T getBy(Map<String, Object> paramMap) {
		if(paramMap == null){
			return null;
		}
		return this.getSqlSession().selectOne(getStatement(SQL_LIST_BY),paramMap);
	}

	public List<T> listBy(Map<String, Object> paramMap) {
		if(paramMap == null){
			return null;
		}
		return this.getSqlSession().selectList(getStatement(SQL_LIST_BY),paramMap);
	}

	public List<T> listByColumn(Map<String, Object> paramMap) {
		if(paramMap == null){
			return null;
		}
		return this.getSqlSession().selectList(getStatement(SQL_LIST_BY_COLUMN), paramMap);
	}

	public Long getCountByColumn(Map<String, Object> paramMap) {
		if(paramMap == null){
			return null;
		}
		return this.getSqlSession().selectOne(getStatement(SQL_LIST_PAGE_COUNT),paramMap);
	}

	public int delete(String id) {
		return this.getSqlSession().delete(getStatement(SQL_DELETE_BY_ID), id);
	}

	public int delete(List<T> list) {
		if(list.isEmpty() || list.size() == 0){
			return 0;
		}
		return this.getSqlSession().delete(SQL_DELETE_BY_IDS, list);
	}

	public int delete(Map<String, Object> paramMap) {
		if(paramMap.isEmpty() || paramMap.size() == 0){
			return 0;
		}
		return this.getSqlSession().delete(getStatement(SQL_BATCH_DELETE_BY_COLUMN), paramMap);
	}
	/**
	 * 分页查询
	 */
	public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) {
		if(paramMap == null){
			paramMap = new HashMap<String,Object>();
		}
		//统计总记录数
		Long totalCount =this.getSqlSession().selectOne(getStatement(SQL_LIST_PAGE_COUNT),paramMap); 
	
        // 校验当前页数
        int currentPage = PageBean.checkCurrentPage(totalCount.intValue(), pageParam.getNumPerPage(), pageParam.getPageNum());
        pageParam.setPageNum(currentPage); // 为当前页重新设值
        // 校验页面输入的每页记录数numPerPage是否合法
        int numPerPage = PageBean.checkNumPerPage(pageParam.getNumPerPage()); // 校验每页记录数
        pageParam.setNumPerPage(numPerPage); // 重新设值

        // 根据页面传来的分页参数构造SQL分页参数
        paramMap.put("pageFirst", (pageParam.getPageNum() - 1) * pageParam.getNumPerPage());
        paramMap.put("pageSize", pageParam.getNumPerPage());
        paramMap.put("startRowNum", (pageParam.getPageNum() - 1) * pageParam.getNumPerPage());
        paramMap.put("endRowNum", pageParam.getPageNum() * pageParam.getNumPerPage());

        // 获取分页数据集
        List<Object> list =this.getSqlSession().selectList(getStatement(SQL_LIST_PAGE), paramMap);

        Object isCount = paramMap.get("isCount"); // 是否统计当前分页条件下的数据：1:是，其他为否
        if (isCount != null && "1".equals(isCount.toString())) {
            Map<String, Object> countResultMap =this.getSqlSession().selectOne(getStatement(SQL_COUNT_BY_PAGE_PARAM), paramMap);
            return new PageBean<Object>(pageParam.getPageNum(), pageParam.getNumPerPage(), totalCount.intValue(), list, countResultMap);
        } else {
            // 构造分页对象
            return new PageBean<Object>(pageParam.getPageNum(), pageParam.getNumPerPage(), totalCount.intValue(), list);
        }
		
	}

	
	/**
	 * 函数功能说明: 获得mapper 的命名空间
	 * @param sqlId
	 * @return
	 */
	public String getStatement(String sqlId){
		String name = this.getClass().getName();
		//单线程StringBuilder 确保速度;多线程 StringBuffer 确保安全
		StringBuilder builder = new StringBuilder();
		builder.append(name).append(".").append(sqlId);
		return builder.toString();
		
	}
}
